<template>
    <div class="recipe_list">
        <el-container>
            <el-header>
                <page-title>处方单列表</page-title>
            </el-header>
            <div style="padding:0 60px;" class="text-right"> <el-button   @click="exportExcel">导出表格</el-button> </div>
            <el-main class="content">
                <div class="search_box">
                    <el-row :gutter="20" style="min-width:1024px">
                        <el-col :span="6">
                            订单编号：<el-input v-model="searchForm.order_no" style="width:50%"></el-input>
                        </el-col>
                        <el-col :span="6">
                            处方单状态：
                            <el-select v-model="searchForm.status" placeholder="请选择" style="width:50%">
                                <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="6">
                            提交时间：
                            <el-date-picker
                                v-model="searchForm.create_time"
                                type="daterange"
                                align="center"
                                unlink-panels
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                :default-value="new Date() - (30*24*60*60*1000)"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                :default-time="['00:00:00', '23:59:59']"
                                :picker-options="pickerOptions"
                                style="width: 64%">
                            </el-date-picker>
                        </el-col>
                        <el-col :span="6">
                            <el-button type="primary" @click="getData">查询结果</el-button>
                        </el-col>
                    </el-row>
                </div>

                <div class="table_box">
                    <el-table
                        :data="tableData"
                        border
                        style="width: 100%">
                        <el-table-column
                            prop="order_no"
                            label="订单编号"
                            min-width="120">
                        </el-table-column>

                        <el-table-column
                            prop="user.user_name"
                            label="患者姓名">
                        </el-table-column>

                        <el-table-column
                            prop="subscribes.age"
                            label="患者年龄"
                            width="100">
                        </el-table-column>

                        <el-table-column
                            prop="subscribes.description"
                            label="病情简介"
                            min-width="200">
                        </el-table-column>

                        <el-table-column
                            prop="remark"
                            label="医嘱"
                            min-width="200">
                        </el-table-column>

                        <el-table-column
                            prop="create_time"
                            label="时间"
                            min-width="120"
                            show-overflow-tooltip>
                        </el-table-column>

                        <el-table-column
                            label="状态"
                            show-overflow-tooltip>
                            <template slot-scope="scope">
                                <span>{{scope.row.status == 0 ? '待审核' : scope.row.status == 1 ? '待付款' : scope.row.status == 2 ? '待发货' : scope.row.status == 3 ? '已发货' : '已驳回'}}</span>
                            </template>
                        </el-table-column>

                        <el-table-column
                            align="center"
                            label="操作"
                            width="180">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" @click="recipeDetails(scope.row)">查看处方单</el-button>
                                <el-button type="text" size="small" @click="order(scope.row)" >订单详情</el-button>
                                <span v-show="limitedShow.indexOf('3.1')!=-1">
                                    <el-button type="text" size="small" @click="pass(scope.row.id,scope.row.uid)" :disabled="scope.row.status != 0 && scope.row.status != '98'">审核通过</el-button>
                                    <el-button type="text" size="small" @click="reject(scope.row.id)" :disabled="scope.row.status != 0">审核驳回</el-button>
                                </span> 
                            </template>
                        </el-table-column>
                    </el-table>

                    <div class="pagination_box">
                        <el-pagination
                            layout="prev, pager, next"
                            :total="total"
                            :page-size = "pageSize"
                            @current-change="setCurrentPage">
                        </el-pagination>
                    </div>
                </div>
            </el-main>
        </el-container>
    </div>
</template>

<script> 
import * as api from './../../../api/api'
//导出excel
import FileSaver from 'file-saver'
import XLSX from 'xlsx' 
export default {
    data() {
        return{
            limitedShow:sessionStorage.getItem('models').split(','),
            //--------搜索相关---------
            searchForm: {
                order_no: '',//处方单编号
                status: '',//订单来源
                create_time: '',//时间段
            },
            options: [],
            //日期选择器配置
            pickerOptions: {
                disabledDate(date) {
                    return date && date.valueOf() > Date.now() + 1000*60*60*24;
                }
            },
            //-------表格相关------
            tableData: [],//表格数据
            exportDataList:[], //导出数据
            total: 0,//数据总条数
            offset: 0,//显示的页
            pageSize: 10,//每页显示条数
        }
    },

    created() { 
        console.log(this.limitedShow );
        if(this.limitedShow.indexOf('3.1')!=-1&&this.limitedShow.indexOf('3.2')!=-1&&this.limitedShow.indexOf('3')!=-1){  
            this.options=[  
                { value: '', label: '全部' },
                { value: '98',label: '已驳回'},
                { value: '3', label: '已发货'},
                {value: '1',label: '待付款'},
                { value: '0', label: '待审核'},
                {value: '2',label: '待发货'}
            ]; 
            this.searchForm.status=''
        }else if(this.limitedShow.indexOf('3.1')!=-1&&this.limitedShow.indexOf('3.2')!=-1&&this.limitedShow.indexOf('3')==-1){
            this.options=[ { value: '0', label: '待审核'}, {value: '2',label: '待发货'}]; 
            this.searchForm.status='0'
        }else if(this.limitedShow.indexOf('3.1')==-1&&this.limitedShow.indexOf('3.2')!=-1&&this.limitedShow.indexOf('3')==-1){  
            this.options=[   {value: '2',label: '待发货'} ]; 
            this.searchForm.status='2'
        }else if(this.limitedShow.indexOf('3.1')!=-1&&this.limitedShow.indexOf('3.2')==-1&&this.limitedShow.indexOf('3')==-1){  
            this.options=[{ value: '0', label: '待审核'} ]; 
            this.searchForm.status='0'
        }else if(this.limitedShow.indexOf('3.1')!=-1&&this.limitedShow.indexOf('3.2')==-1&&this.limitedShow.indexOf('3')!=-1){  
            this.options=[  
                { value: '', label: '全部' },
                { value: '98',label: '已驳回'},
                { value: '3', label: '已发货'},
                {value: '1',label: '待付款'},
                { value: '0', label: '待审核'}
            ]; 
            this.searchForm.status=''
        }else if(this.limitedShow.indexOf('3.1')==-1&&this.limitedShow.indexOf('3.2')!=-1&&this.limitedShow.indexOf('3')!=-1){  
            this.options=[  
                { value: '', label: '全部' },
                { value: '98',label: '已驳回'},
                { value: '3', label: '已发货'},
                {value: '1',label: '待付款'},
                {value: '2',label: '待发货'}
            ]; 
            this.searchForm.status=''
        }if(this.limitedShow.indexOf('3.1')==-1&&this.limitedShow.indexOf('3.2')==-1&&this.limitedShow.indexOf('3')!=-1){  
            this.options=[  
                { value: '', label: '全部' },
                { value: '98',label: '已驳回'},
                { value: '3', label: '已发货'},
                {value: '1',label: '待付款'} 
            ]; 
            this.searchForm.status=''
        } 
    },

    //钩子函数（页面挂载完成时触发）
    mounted() {
        this.getData()
    },

    //自定义方法
    methods: {
        //导出excel
        exportExcel () {  
           const defaultCellStyle =  { font: { name: "Verdana", sz: 11, color: "FF00FF88"}, fill: {fgColor: {rgb: "FFFFAA00"}}};
            const wopts = { bookType:'xlsx', bookSST:false, type:'binary', defaultCellStyle: defaultCellStyle, showGridLines: false};
            const wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} }; 
            let data = this.exportDataList
            wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(data)
            //创建二进制对象写入转换好的字节流
            let tmpDown =  new Blob([this.s2ab(XLSX.write(wb, wopts))], { type: "application/octet-stream" })
            FileSaver.saveAs(tmpDown, "处方单列表.xls"); 
       },
       //字符串转字符流
        s2ab (s) {
            if (typeof ArrayBuffer !== 'undefined') {  
                var buf = new ArrayBuffer(s.length);  
                var view = new Uint8Array(buf);  
                for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;  
                return buf;  
            } else {  
                var buf = new Array(s.length);  
                for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;  
                return buf;  
            }
        },
        //获取数据
        getData() {
            let vm = this;
            let searchForm = {};
            if(vm.searchForm.order_no !== '') {
                searchForm.order_no = vm.searchForm.order_no
            }
            if(vm.searchForm.status !== '') {
                searchForm.status = vm.searchForm.status;
            }
            // if()
            if(vm.searchForm.create_time !== '' && vm.searchForm.create_time !== null) {
                searchForm.create_time = vm.searchForm.create_time
            }
            let body = {
                model: "Orders",
                with:{
                    0:"user",
                    1:"subscribes",
                    2:"doctor",
                    3:"address"
                },
                limit: vm.pageSize,
                offset:vm.offset,
                orderBy:"create_time desc",
                condition:searchForm
            };
            if(body.condition.create_time) {
                let time = body.condition.create_time;
                let newTime = "";
                for (let index = 0; index < time.length; index++) {
                    let one = time[index];
                    let time1 = one.split(' ')[0];
                    if(index === 1){
                        newTime = newTime + '&' + time1 + ',between';
                    }else{
                        newTime = newTime + time1;
                    }
                }
                body.condition.create_time = newTime;
            };
            api.getDateList(body).then(res=>{
                if(res.data.code==200){
                    vm.tableData = res.data.data.data;
                    vm.total = res.data.data.count * 1;
                    let arrList=[];
                    res.data.data.data.forEach((item,index)=>{
                        let obj={};
                        obj['订单单号']=item.order_no;
                        obj['开单时间']=item.create_time;
                        obj['患者姓名']=item.user.user_name;
                        
                        if(item.subscribes){
                            obj['患者年龄']=item.subscribes.age;
                            obj['病情简介']=item.subscribes.description;
                        }else{
                            obj['患者年龄']='';
                            obj['病情简介']='';    
                        }  
                        obj['处方内容']=item.content; 
                        obj['处方说明']=item.decide; 
                        obj['医生姓名']=item.doctor.name;
                        obj['医嘱']=item.remark; 
                        obj['订单状态']=item.status == 0 ? '待审核' : item.status == 1 ? '待付款' : item.status == 2 ? '待发货' : item.status == 3 ? '已发货' : '已驳回';
                        arrList.push(obj);
                    });
                    // console.log(arrList);
                    vm.exportDataList=arrList;
                }
            });
        },
        //分页
        setCurrentPage(currentPage) {
            this.offset = currentPage - 1;
            this.getData();
        },

        //查看处方单
        recipeDetails(row) {
            let data = row;
            let recipe = JSON.stringify(row);
            this.$router.push({name:'Recipe',query:{recRow:recipe}})
        },

        //查看订单详情
        order(row) {
            let data = row;
            let recipe = JSON.stringify(row);
            this.$router.push({name: 'OrderDetails',query:{recipe}})
        },

        //审核通过
        pass(id,uid) {
            let body = {
                model: "Orders",
                data: {
                    status: '1'
                },
                update_condition: {
                    id,
                    uid
                }
            };
            this.$confirm('你确定要通过该订单吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                api.createData(body).then(res => {
                    if(res.data.code === 200) {
                        this.$message({
                            message: '恭喜你，操作成功',
                            type: 'success'
                        });
                        this.getData()
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });          
            });
        },

        //审核驳回
        reject(id) {
            let body = {
                model: "Orders",
                data: {
                    status: '98'
                },
                update_condition: {
                    id
                }
            };
            this.$confirm('你确定要驳回该订单吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                api.createData(body).then(res => {
                    if(res.data.code === 200) {
                        this.$message({
                            message: '恭喜你，操作成功',
                            type: 'success'
                        });
                        this.getData()
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });          
            });
            
        }
    },

    //注册组件
    components: {

    }
}
</script>

<style lang="scss">
    .recipe_list{
        .el-header{
            padding: 0;
        }
        .el-date-editor .el-range-separator{
            width: 20px;
        }
        .el-table__header tr th{
            background-color: #f6f6f6;
        }
        .content{
            padding: 20px 80px;
            overflow: hidden;
            .table_box{
                margin-top: 40px;
            }
            .pagination_box{
                padding: 4px;
                display: flex;
                justify-content: flex-end;
                background-color: #f6f6f6;
                border: 1px solid #eee;
                border-top: none;
                .checkedAll{
                    line-height: 40px;
                    margin-left: 6px;
                }
            }
        }
    }
</style>
